package com.shaonianyou.component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

public class CustUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

	public static final String SPRING_SECURITY_FORM_SPLIT_CHAR = "/";

	public CustUsernamePasswordAuthenticationFilter() {
		super();
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException {
		if (!request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
		}

		String idcard = request.getParameter("idcard") == null ? "" : request.getParameter("idcard");
		String mobile = request.getParameter("mobile") == null ? "" : request.getParameter("mobile");
		String code = request.getParameter("code") == null ? "" : request.getParameter("code");
		String openid = request.getParameter("openid") == null ? "" : request.getParameter("openid");

		String username = idcard + SPRING_SECURITY_FORM_SPLIT_CHAR + mobile + SPRING_SECURITY_FORM_SPLIT_CHAR + code + SPRING_SECURITY_FORM_SPLIT_CHAR + openid;

		UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, code);

		// Allow subclasses to set the "details" property
		setDetails(request, authRequest);
		return this.getAuthenticationManager().authenticate(authRequest);
	}

}
